const http = require("http");
const url = require("url");
const qs = require("querystring");

const server = http.createServer((req, res) => {
  // 获取请求头
  console.log(req.headers);
  console.log(req.headers["content-type"]);
  // cookie/session/token
  const token = req.headers["authorization"];

  // 1.参数一: query类型参数
  // /home/list?offset=100&size=20
  // 1. 解析url
  const urlString = req.url;
  const urlInfo = url.parse(urlString); // 解析url

  // 1.2.解析query: offset=100&size=20
  const queryString = urlInfo.query;
  const queryInfo = qs.parse(queryString); // 解析query
  console.log(queryInfo.offset, queryInfo.size);

  // 2.参数二: body类型参数
  req.setEncoding("utf-8");
  // 2.1.获取请求方法
  // request对象本质是上一个readable可读流
  let isLogin = false;
  req.on("data", (data) => {
    const loginInfo = JSON.parse(data);
    if (loginInfo.username === "admin" && loginInfo.password === "123456") {
      isLogin = true;
    } else {
      isLogin = false;
    }
  });

  req.on("end", () => {
    if (isLogin) {
      res.end("登录成功, 欢迎回来~");
    } else {
      res.end("账号或者密码错误, 请检测登录信息~");
    }
  });

  res.end("hello response");
});

server.listen(8080, () => {
  console.log("server is running on http://localhost:8080");
});
